<script setup lang="ts">
//导入
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder:{
    type: String,
    default: ''
  },
  maxlength:{
    type: Number,
    default: null
  }
})
const inputVal = ref('')
const maxLenVal = ref('')
const inputer = ref<HTMLElement>()
//ref、reactive、自定义变量

//hooks
const emits = defineEmits<{
  (e: 'update:modelValue', val: string): void
}>()
function handleInput(e:any){
  const innerText = inputer?.value?.textContent || ''
  if(props.maxlength) {
    if(innerText.length < props.maxlength){
      inputVal.value = innerText
    }else if(innerText.length === props.maxlength){
      maxLenVal.value = innerText
    }else{
      inputVal.value = maxLenVal.value
      inputer!.value!.innerText = maxLenVal.value
    }
  }else{
    inputVal.value = inputer?.value?.textContent || ''
  }
  emits('update:modelValue',inputVal.value)
}
watch(
  () => props.modelValue,
  (val) => {
    inputVal.value = val
  })
function focus(){
  inputer?.value?.focus()
}
onMounted(()=> {
  if(props.modelValue) {
    inputVal.value = props.modelValue;

  }
})
defineExpose({
  focus
})
//方法
</script>

<template>
<p ref="inputer" class="p-2" contenteditable="true" @input="handleInput">{{inputVal}}</p>
</template>

<style scoped lang="scss">
p{
  outline: 1px solid #18a058;
  border-radius: 2px;
  transition: all .3s;
  white-space: pre-wrap;
  width: 100%;
}
p:focus-visible,p:hover{
  outline: 1px solid #18a058;
  //box-shadow: 0 0 0 2px rgba(24, 160, 88, 0.2);
  box-shadow: 0 0 0 2px rgba(24, 160, 88, 0.2) inset;
}
</style>